package com.ruix.app.ui.main;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import com.ruix.app.R;
import com.ruix.app.RuiApplication;
import com.ruix.app.cache.CacheFactory;
import com.ruix.app.manager.ClientInfo;
import com.ruix.app.manager.UserManager;
import com.ruix.app.mapper.OssTokenMapper;
import com.ruix.app.mapper.SystemConfigMapper;
import com.ruix.app.mapper.UserMapper;
import com.ruix.app.model.AppUpgradeConfig;
import com.ruix.app.model.Classes;
import com.ruix.app.model.Lesson;
import com.ruix.app.model.OssToken;
import com.ruix.app.model.SystemConfig;
import com.ruix.app.network.DefaultRXObserver;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.service.UpdateAppService;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.ui.stratum.ClassesStratumActivity;
import com.ruix.app.ui.stratum.lesson.CaseLearningActivity;
import com.ruix.app.ui.stratum.notice.NotifyListActivity;
import com.ruix.app.util.SoftInputUtil;
import com.ruix.app.widget.TabItemView;
import com.ruix.app.widget.dialog.CommonDialog;

import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.disposables.Disposable;

public class MainActivity extends BaseActivity implements TabItemView.OnClickListener{

    private TabItemView tabGrade, tabMessage, babUserCenter, tmpItem;
    private FragmentManager fragmentManager;
    private GradeFragment gradeFragment;
    private AppUpgradeConfig appUpgradeConfig;

    private final String TAG_FRAGMENT_GRADE = "tag_grade";
    private final String TAG_FRAGMENT_MESSAGE = "tag_message";
    private final String TAG_FRAGMENT_USERCENTER = "tag_usercenter";

//    private BroadcastReceiver myReceiver = new BroadcastReceiver(){
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            if (RuiXConstant.NOTICE_LOGOUT.equals(intent.getAction())){
//                redirectLogin();
//                //
//            }
//        }
//
//    };


    @Override
    protected int loadViewLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        tabGrade = (TabItemView) findViewById(R.id.tab_grade);
        tabMessage = (TabItemView) findViewById(R.id.tab_message);
        babUserCenter = (TabItemView) findViewById(R.id.tab_user_center);
        fragmentManager = getSupportFragmentManager();



        addGradeFragment();
    }

    @Override
    protected void initLocalData() {
        getOssToken();
        //TODO
        String alias = "ruix_" + UserManager.getCurrentUser().getID();
        JPushInterface.setAlias(this,1,alias);

        handelPushMessage(getIntent());
        laodSystemInfo();
    }

    @Override
    protected void initListener() {
        tabGrade.setClickListener(this);
        tabMessage.setClickListener(this);
        babUserCenter.setClickListener(this);
//        registerReceivers();
    }

    @Override
    protected boolean isUseBaseTitleBar() {
        return false;
    }

    @Override
    protected boolean isUseNavigaBar() {
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tab_grade:
                if (tmpItem != tabGrade) {
                    setTabItemViewStatus(tabGrade);
                    switchToGrade();
                }
                break;

            case R.id.tab_message:
                if (tmpItem != tabMessage) {
                    setTabItemViewStatus(tabMessage);
                    switchToMessage();
                }



                break;
            case R.id.tab_user_center:
                if (tmpItem != babUserCenter) {
                    setTabItemViewStatus(babUserCenter);
                    switchToUserCenter();
                }
                break;
        }
    }

    private void setTabItemViewStatus(TabItemView tabItemView) {
        if (tmpItem != null) {
            tmpItem.setSelectedStatus(false);
        }
        tabItemView.setSelectedStatus(true);
        tmpItem = tabItemView;

    }

    private void addGradeFragment() {
        if (gradeFragment == null) {
            gradeFragment = new GradeFragment();
        }
        setUserVisibleHintProxy(gradeFragment, true);
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.rl_main_fragment_container, gradeFragment, TAG_FRAGMENT_GRADE);
        transaction.commitAllowingStateLoss();
        setTabItemViewStatus(tabGrade);
    }

    private void switchToGrade() {
        GradeFragment fragmentGrade = (GradeFragment) fragmentManager.findFragmentByTag(TAG_FRAGMENT_GRADE);
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if (fragmentGrade != null && fragmentGrade.isAdded()) {
            transaction.show(fragmentGrade);
        } else if (fragmentGrade != null && fragmentGrade.isDetached()) {
            transaction.attach(fragmentGrade);
            transaction.show(fragmentGrade);
        } else {
            if (fragmentGrade == null) {
                fragmentGrade = new GradeFragment();
            }
            transaction.add(R.id.rl_main_fragment_container, fragmentGrade, TAG_FRAGMENT_GRADE);
        }
        setUserVisibleHintProxy(fragmentGrade, true);
        detachMessage(transaction);
        detachUserCenter(transaction);
        transaction.commitAllowingStateLoss();
        fragmentGrade.onResume();
    }


    private void detachGrade(FragmentTransaction transaction) {
        GradeFragment fragmentGrade = (GradeFragment) fragmentManager.findFragmentByTag(TAG_FRAGMENT_GRADE);
        if (fragmentGrade != null && fragmentGrade.isAdded()) {
            transaction.hide(fragmentGrade);
            fragmentGrade.onPause();
            fragmentGrade.setUserVisibleHint(false);
//            transaction.detach(fragmentLinkedDevice);
        }

    }

    private void switchToMessage() {
        MessageFragment fragmentMessage = (MessageFragment) fragmentManager.findFragmentByTag(TAG_FRAGMENT_MESSAGE);
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if (fragmentMessage != null && fragmentMessage.isAdded()) {
            transaction.show(fragmentMessage);
        } else if (fragmentMessage != null && fragmentMessage.isDetached()) {
            transaction.attach(fragmentMessage);
            transaction.show(fragmentMessage);
        } else {
            if (fragmentMessage == null) {
                fragmentMessage = new MessageFragment();
            }
            transaction.add(R.id.rl_main_fragment_container, fragmentMessage, TAG_FRAGMENT_MESSAGE);
        }
        setUserVisibleHintProxy(fragmentMessage, true);
        detachGrade(transaction);
        detachUserCenter(transaction);
        transaction.commitAllowingStateLoss();
        fragmentMessage.onResume();
    }

    private void detachMessage(FragmentTransaction transaction) {
        MessageFragment fragmentMessage = (MessageFragment) fragmentManager.findFragmentByTag(TAG_FRAGMENT_MESSAGE);
        if (fragmentMessage != null && fragmentMessage.isAdded()) {
            transaction.hide(fragmentMessage);
            fragmentMessage.onPause();
            fragmentMessage.setUserVisibleHint(false);
//            transaction.fragmentToolbox(fragmentToolbox);
        }
    }

    private void switchToUserCenter() {
        UserCenterFragment fragmentUserCenter = (UserCenterFragment) fragmentManager.findFragmentByTag(TAG_FRAGMENT_USERCENTER);
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if (fragmentUserCenter != null && fragmentUserCenter.isAdded()) {
            transaction.show(fragmentUserCenter);
        } else if (fragmentUserCenter != null && fragmentUserCenter.isDetached()) {
            transaction.attach(fragmentUserCenter);
            transaction.show(fragmentUserCenter);
        } else {
            if (fragmentUserCenter == null) {
                fragmentUserCenter = new UserCenterFragment();
            }
            transaction.add(R.id.rl_main_fragment_container, fragmentUserCenter, TAG_FRAGMENT_USERCENTER);
        }
        setUserVisibleHintProxy(fragmentUserCenter, true);
        detachGrade(transaction);
        detachMessage(transaction);
        transaction.commitAllowingStateLoss();
        fragmentUserCenter.onResume();
    }

    private void detachUserCenter(FragmentTransaction transaction) {
        UserCenterFragment fragmentUserCenter = (UserCenterFragment) fragmentManager.findFragmentByTag(TAG_FRAGMENT_USERCENTER);
        if (fragmentUserCenter != null && fragmentUserCenter.isAdded()) {
            transaction.hide(fragmentUserCenter);
            fragmentUserCenter.onPause();
            fragmentUserCenter.setUserVisibleHint(false);
//            transaction.detach(fragmentLinkedDevice);
        }

    }

    private void setUserVisibleHintProxy(Fragment proxy, boolean state) {
        if (proxy != null) {
            proxy.setUserVisibleHint(state);
        }
    }

    private void getOssToken(){
        RequestFactory.getOssToken(new OssTokenMapper(), new DefaultRXObserver<OssToken>());
    }


//    private void registerReceivers(){
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(RuiXConstant.NOTICE_LOGOUT);
//        registerReceiver(myReceiver, filter);
//    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        unregisterReceivers();
    }

//    private void unregisterReceivers(){
//        if (myReceiver != null){
//            unregisterReceiver(myReceiver);
//        }
//    }

//    private void redirectLogin() {
//        Intent intent = new Intent(this, LoginActivity.class);
//        startActivity(intent);
//        finish();
//        // remove
//    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            moveTaskToBack(true);// 点击菜单键即转入后台，vivo X6Plus Android5.1也适用
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null){
           String action =  intent.getStringExtra("ACTION");
            if ("CLASS_DETAIL".equals(action)){
                 String cid =  intent.getStringExtra("CID");
                if (!TextUtils.isEmpty(cid)) {
                    Classes classes = new Classes();
                    classes.setID(cid);
                    UserManager.sharedInstance().setCurrentClass(classes);
                    Intent classInntent = ClassesStratumActivity.newIntent(this, classes,null);
                    startActivity(classInntent);
                }
            }
            handelPushMessage(intent);
        }
    }


    private void handelPushMessage(Intent intent){
        if (intent != null){
            String pushExtrea = intent.getStringExtra(JPushInterface.EXTRA_EXTRA);
            if (!TextUtils.isEmpty(pushExtrea)){
                try {
                    JSONObject object = new JSONObject(pushExtrea);
                    String pushAction =  object.optString("to","");
                    String cid =  object.optString("cid","");
                    if (!TextUtils.isEmpty(pushAction) && !TextUtils.isEmpty(cid)){
                        Classes currentClasses = new Classes();
                        currentClasses.setID(cid);
                        if ("course".equals(pushAction)){ //案例学习列表页
                            UserManager.sharedInstance().setCurrentClass(currentClasses);
                            startActivity(ClassesStratumActivity.newIntent(this, currentClasses,"message"));
                        } else if ("notice".equals(pushAction)){ //通知列表页
                            startActivity(NotifyListActivity.newIntent(this,currentClasses,"message"));
                        } else if ("lesson".equals(pushAction)){//案例学习详情
                            String lid =  object.optString("lid","");
                            if (!TextUtils.isEmpty(lid)){
                                Lesson lesson = new Lesson();
                                lesson.setId(lid);
                                UserManager.sharedInstance().setCurrentLesson(lesson);
                                startActivity(CaseLearningActivity.newIntent(this,lesson,currentClasses,"message"));
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }



    private void checkAppUpgrade(){
        if (appUpgradeConfig != null
                && !TextUtils.isEmpty(appUpgradeConfig.getLatestVersionUrl())
                && !ClientInfo.isHintAppUpgrae(appUpgradeConfig.getLatestVersion()) //未提示过
                && appUpgradeConfig.isNeedUpgrade(RuiApplication.appVersionCode)) {
            showUpgradeDialog();
            ClientInfo.setHintAppUpgrae(appUpgradeConfig.getLatestVersion());
        }

    }

    private void showUpgradeDialog(){
            CommonDialog dialog = new CommonDialog(this);
            dialog.setListener(new CommonDialog.CommonDialogAcitonListener() {
                @Override
                public void positiveAction() {
                    webUpgrade();
                }

                @Override
                public void negertivieAction() {

                }
            });
            dialog.show("当前版本非最新版本，建议更新。");
            dialog.setPositiveString("立即更新");
            dialog.seCancelString("忽略此版本");
            dialog.setCancelStringColor(0xFFAAAAAA);

    }


    private void webUpgrade(){
        if (appUpgradeConfig != null && appUpgradeConfig.getLatestVersionUrl() != null && appUpgradeConfig.isNeedUpgrade(RuiApplication.appVersionCode)) {
//            Intent intent = new Intent();
//            intent.setAction("android.intent.action.VIEW");
//            Uri content_url = Uri.parse(appUpgradeConfig.getLatestVersionUrl());
//            intent.setData(content_url);
//            startActivity(intent);
            downloadApk(appUpgradeConfig.getLatestVersionUrl());
        }
    }

    private void laodSystemInfo() {
        RequestFactory.systemInfo(new SystemConfigMapper(), new RXObserver<SystemConfig>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(SystemConfig value) {
                if (value != null) {
                    appUpgradeConfig = value.getAppUpgradeConfig();
                    if (appUpgradeConfig != null){
                        CacheFactory.cacheAppUpgradeConfig(appUpgradeConfig);////缓存 离线下载
                        checkAppUpgrade();
                    }
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }
    private void downloadApk(String url){
        UpdateAppService.Builder.create(url)
                .setOnlyOnWifiWork(false)
                .setShowNotify(true)
                .setAutoUpdate(true)
                .build(this);

    }


    @Override
    protected void onResume() {
        super.onResume();
        loadMessageState();
    }

    private void loadMessageState() {
        RequestFactory.getMessageUnreaded(null, new RXObserver<JSONObject>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(JSONObject value) {
                if (value != null) {
                    JSONObject data = value.optJSONObject("data");
                    if (data != null) {
                        int num = data.optInt("num", 0);
                        if (tabMessage != null) {
                            tabMessage.setNewMessageState(num > 0);
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

    }
}
